#coding=utf-8
'''
Created on 2017-06-13

@author: sandy

'''
import logging
from pycommon import LogManager
from pycommon import Const
from pycommon import Utils
from pycommon import Pack as packet
import ClientFactory
import ClientBuild
import os
import zlib
import json
import hashlib
import FileUpdateManager

def cmdLogin(client,pkt):
    sid = packet.unpack("H",pkt)
    oldClient = ClientFactory.instance.getClientSrvBySid(sid)
    if oldClient == None:
        logging.debug(u'sid=%d register sucess',sid)
        client.sendPacket(ClientBuild.loginManager(Const.ERR_OK))
        client.onLogin(sid)
    else:
        logging.debug(u'sid=%d register Failed,server is exist',sid)
        client.sendPacket(ClientBuild.loginManager(Const.ERR_SERVER_EXIST))

def cmdGetConfig(client,pkt):
    cfgname = packet.unpack("s",pkt)
    logging.debug(u"cmdGetConfig cfgName = %s",cfgname)
    fileNames = []
    pathList = cfgname.split('.')
    if pathList[-1] == "*":
        dirPaths = pathList[:-1]
        dirPathstr = os.path.join(*dirPaths)
        for li in os.listdir(dirPathstr):
            filePathStr = dirPathstr + os.sep + li
            fileNames.append(filePathStr)
    else:
        dirPathstr = os.path.join(*pathList)
        filePathStr = dirPathstr +".json"
        fileNames.append(filePathStr)
    
    for file in fileNames:
        f = open(file)
        content = f.read()
        f.close()
        strContent = zlib.compress(content)
        name = file.replace(os.sep,'.')[:-5]
        logging.debug(u"cmdGetConfig sid = %d cfgname = %s",client.getSId(),name)
        client.sendPacket(ClientBuild.sendConfig(name,strContent))
        FileUpdateManager.instance.addFlagToMap(client.getSId(),name)


def cmdUploadHotFile(client,pkt):   
    cfgname,md5str,content,updateServerSids = packet.unpack("ssSs",pkt)
    logging.debug(u"cmdUploadHotFile cfgname = %s,md5str = %s",cfgname,md5str)
    serversList = updateServerSids.split(",")
    decontent = zlib.decompress(content)
    md5NewStr = hashlib.md5(decontent).hexdigest()
    if md5NewStr == md5str:
        for i in serversList:
            hotclient = ClientFactory.instance.getClientSrvBySid(int(i))
            if hotclient:
                hotclient.sendPacket(ClientBuild.hotUpdateFile(cfgname,md5str,content))
                client.sendPacket(ClientBuild.hotUpdateFileRet(cfgname,"sid = %s server sucess" % i))
            else:
                logging.debug(u"sid = %s client not found", i)
                client.sendPacket(ClientBuild.hotUpdateFileRet(cfgname,"sid = %s server not found" % i))
        pass
    else:
        client.sendPacket(ClientBuild.hotUpdateFileRet(cfgname,"md5 not sample"))

def cmdGetConfigEnd(client,pkt):
    client.sendPacket(ClientBuild.sendConfigFin())


def cmdUploadConfigFile(client,pkt):
    cfgname,md5str,content = packet.unpack("ssS",pkt)
    logging.debug(u"cmdUploadConfigFile cfgname = %s,md5str = %s",cfgname,md5str)
    content = zlib.decompress(content)
    md5NewStr = hashlib.md5(content).hexdigest()
    if md5NewStr == md5str:
        pathList = cfgname.split('.')
        dirPathstr = os.path.join(*pathList)
        filePathStr = dirPathstr +".json"
        logging.debug(u"filePathStr = %s",filePathStr)
        f = open(filePathStr)
        serverContent = f.read()
        f.close()
        serverMd5 = hashlib.md5(serverContent).hexdigest()
        if md5NewStr == serverMd5:
            logging.debug(u"upload file %s failed,file is new",cfgname)
            client.sendPacket(ClientBuild.uploadFile(cfgname,"file is new"))
        else:
            f = open(filePathStr,"w")
            f.write(content)
            f.close()
            logging.debug(u"upload file %s sucess",cfgname)
            client.sendPacket(ClientBuild.uploadFile(cfgname,"upload sucess"))
            #下发更新文件到各个服务器
            FileUpdateManager.instance.updateFile(cfgname,content)
    else:
        logging.debug(u"upload file %s failed,md5 not sample",cfgname)
        client.sendPacket(ClientBuild.uploadFile(cfgname,"md5 not sample"))
    pass

__cmdTable = {
              Const.CMD_XX2MGR_LOGIN                  : cmdLogin,
              Const.CMD_XX2MGR_GET_CONFIG             : cmdGetConfig,
              Const.CMD_XX2MGR_GET_CONFIG_END         : cmdGetConfigEnd,
              Const.CMD_XX2MGR_UPLOAD_CONFIG_FILE     : cmdUploadConfigFile,
              Const.CMD_XX2MGR_HOT_UPLOAD_FILE        : cmdUploadHotFile
             }
def parse(client,cmd,pkt):
    logging.debug(u"ClientParse cmd = %d",cmd)
    func = __cmdTable.get(cmd)
    if not func :
        logging.error(u"unknow cmd=%d" % cmd)
        return
    func(client, pkt)
    pass

